<template>
  <div class="performance-container">
    <div class="performance-panel" v-if="metrics">
      <div class="panel-header" @click="togglePanel">
        <h3>子应用加载性能指标</h3>
        <el-icon class="toggle-icon" :class="{ 'is-collapsed': isCollapsed }">
          <ArrowDown />
        </el-icon>
      </div>
      <div class="panel-content" v-show="!isCollapsed">
        <div class="metrics">
          <div class="metric-group">
            <h4>基础加载时间</h4>
            <div class="metric-item">
              <span class="label">总加载时间:</span>
              <span class="value">{{ metrics.totalTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">挂载时间:</span>
              <span class="value">{{ metrics.mountTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">初始化时间:</span>
              <span class="value">{{ metrics.bootstrapTime }}ms</span>
            </div>
          </div>

          <div class="metric-group">
            <h4>资源加载详情</h4>
            <div class="metric-item">
              <span class="label">JS 加载时间:</span>
              <span class="value">{{ metrics.scriptLoadTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">CSS 加载时间:</span>
              <span class="value">{{ metrics.styleLoadTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">其他资源时间:</span>
              <span class="value">{{ metrics.otherResourceTime }}ms</span>
            </div>
          </div>

          <div class="metric-group">
            <h4>渲染性能</h4>
            <div class="metric-item">
              <span class="label">首次内容绘制(FCP):</span>
              <span class="value">{{ metrics.fcp }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">最大内容绘制(LCP):</span>
              <span class="value">{{ metrics.lcp }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">首次有意义绘制(FMP):</span>
              <span class="value">{{ metrics.fmp }}ms</span>
            </div>
          </div>

          <div class="metric-group">
            <h4>网络性能</h4>
            <div class="metric-item">
              <span class="label">DNS 解析时间:</span>
              <span class="value">{{ metrics.dnsTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">TCP 连接时间:</span>
              <span class="value">{{ metrics.tcpTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">请求响应时间:</span>
              <span class="value">{{ metrics.ttfb }}ms</span>
            </div>
          </div>
        </div>

        <div class="resource-details" v-if="metrics.resourceDetails.length">
          <h4>资源加载详情</h4>
          <div class="resource-table">
            <table>
              <thead>
                <tr>
                  <th>资源名称</th>
                  <th>类型</th>
                  <th>大小</th>
                  <th>加载时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(resource, index) in metrics.resourceDetails" :key="index">
                  <td>{{ resource.name }}</td>
                  <td>{{ resource.type }}</td>
                  <td>{{ formatSize(resource.size) }}</td>
                  <td>{{ resource.duration }}ms</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'

interface Metrics {
  totalTime: number
  mountTime: number
  bootstrapTime: number
  scriptLoadTime: number
  styleLoadTime: number
  otherResourceTime: number
  fcp: number
  lcp: number
  fmp: number
  dnsTime: number
  tcpTime: number
  ttfb: number
  resourceDetails: Array<{
    name: string
    type: string
    size: number
    duration: number
  }>
}

const isCollapsed = ref(true)
const metrics = ref<Metrics>({
  totalTime: 0,
  mountTime: 0,
  bootstrapTime: 0,
  scriptLoadTime: 0,
  styleLoadTime: 0,
  otherResourceTime: 0,
  fcp: 0,
  lcp: 0,
  fmp: 0,
  dnsTime: 0,
  tcpTime: 0,
  ttfb: 0,
  resourceDetails: []
})

const startTime = ref(0)

const togglePanel = () => {
  isCollapsed.value = !isCollapsed.value
}

const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i)) + ' ' + sizes[i]
}

const handleCreated = () => {
  console.log('子应用创建完成')
  startTime.value = performance.now()
  metrics.value.bootstrapTime = Math.round(startTime.value)
}

const handleBeforeMount = () => {
  console.log('子应用即将挂载')
  metrics.value.mountTime = Math.round(performance.now() - startTime.value)
}

const handleMounted = () => {
  console.log('子应用挂载完成')
  metrics.value.totalTime = Math.round(performance.now() - startTime.value)
  
  // 延迟收集性能指标，确保资源加载完成
  setTimeout(() => {
    if (window.performance) {
      const entries = performance.getEntriesByType('resource')
      entries.forEach(entry => {
        const resourceEntry = entry as PerformanceResourceTiming
        if (resourceEntry.initiatorType === 'script') {
          metrics.value.scriptLoadTime += Math.round(resourceEntry.duration)
        } else if (resourceEntry.initiatorType === 'css') {
          metrics.value.styleLoadTime += Math.round(resourceEntry.duration)
        } else {
          metrics.value.otherResourceTime += Math.round(resourceEntry.duration)
        }
        
        metrics.value.resourceDetails.push({
          name: resourceEntry.name,
          type: resourceEntry.initiatorType,
          size: resourceEntry.transferSize,
          duration: Math.round(resourceEntry.duration)
        })
      })
    }
  }, 1000) // 延迟1秒收集，确保资源加载完成
}

onMounted(() => {
  // 使用正确的事件名称
  window.addEventListener('micro-app-created', handleCreated)
  window.addEventListener('micro-app-beforemount', handleBeforeMount)
  window.addEventListener('micro-app-mounted', handleMounted)
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('micro-app-created', handleCreated)
  window.removeEventListener('micro-app-beforemount', handleBeforeMount)
  window.removeEventListener('micro-app-mounted', handleMounted)
})
</script>

<style scoped>
.performance-container {
  margin-bottom: 20px;
}

.performance-panel {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.panel-header {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.toggle-icon {
  transition: transform 0.3s;
}

.toggle-icon.is-collapsed {
  transform: rotate(-180deg);
}

.panel-content {
  padding: 20px;
}

.metrics {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.metric-group {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.metric-group h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 13px;
}

.metric-item .label {
  color: #606266;
}

.metric-item .value {
  color: #409EFF;
  font-weight: 500;
}

.resource-details {
  margin-top: 20px;
}

.resource-details h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
}

.resource-table {
  overflow-x: auto;
}

.resource-table table {
  width: 100%;
  border-collapse: collapse;
}

.resource-table th,
.resource-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #EBEEF5;
}

.resource-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.resource-table td {
  color: #606266;
}
</style> 